package com.starinside.wp.controller.api;

import com.starinside.wp.config.WxMpProperties;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.foundation.vo.FamilyGameDetailVO;
import com.starinside.wp.repository.FamilyGameNativeRepository;
import com.starinside.wp.repository.GrowupNativeRepository;
import com.starinside.wp.service.BindedBabyService;

import com.starinside.wp.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.tomcat.jni.Local;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@RestController
@RequestMapping("/wx/api/materials")
@Api(value = "/wx/api/materials", tags = "参考资料")
public class APIMaterialsController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private WxMpService wxService;

    @Autowired
    private BindedBabyService bindedBabyService;

    @Autowired
    private FamilyGameNativeRepository familyGameNativeRepository;

    @Autowired
    private GrowupNativeRepository growupNativeRepository;

    @Autowired
    public APIMaterialsController(WxMpService wxService) {
        this.wxService = wxService;
    }

    @ApiOperation("月子餐列表")
    @RequestMapping(value = "/newMomsFood", method = RequestMethod.GET)
    public StatusResponse newMomsFoodAPI(HttpServletRequest req, HttpServletResponse resp){
        List items = familyGameNativeRepository.getNewMomsFood();

        return StatusResponse.success(items);
    }

    @ApiOperation("营养厨房支持的月份列表")
    @RequestMapping(value = "/babyKitchen-months", method = RequestMethod.GET)
    public StatusResponse babyKitchenMonthsAPI(HttpServletRequest req, HttpServletResponse resp){
        List items = familyGameNativeRepository.getBabyKitchenSupportedMonth();

        return StatusResponse.success(items);
    }

    @ApiOperation("按月查询营养厨房食谱列表")
    @ApiImplicitParam(name = "month", value="月份，支持列表内的值")
    @RequestMapping(value = "/babyKitchen", method = RequestMethod.GET)
    public StatusResponse babyKitchenAPI(HttpServletRequest req, HttpServletResponse resp, Integer month){

        if(month == null){//for default baby
            WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

            if(loginUser.getParentMobile() != null && loginUser.getDefaultBabyId() != null){
                BindedBabyVO defaultBaby = bindedBabyService.getBindedBaby(loginUser.getDefaultBabyId(), loginUser.getParentMobile());
                month = DateUtil.betweenMonths(new Date(), defaultBaby.getBirthday()) + 1;
            }
        }

        List items = familyGameNativeRepository.getBabyKitchenItemsByMonth(month);

        return StatusResponse.success(items);
    }

    @ApiOperation("亲子游戏支持的月份列表")
    @RequestMapping(value = "/family-game-months", method = RequestMethod.GET)
    public StatusResponse familyGameMonthsAPI(HttpServletRequest req, HttpServletResponse resp){
        List items = familyGameNativeRepository.getFamilyGameSupportedMonth();

        return StatusResponse.success(items);
    }

    @ApiOperation("按月查询亲子游戏列表")
    @ApiImplicitParam(name = "month", value="月份，支持列表内的值")
    @RequestMapping(value = "/family-game", method = RequestMethod.GET)
    public StatusResponse familyGameAPI(HttpServletRequest req, HttpServletResponse resp, Integer month){

        if(month == null){//for default baby
            WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

            if(loginUser.getParentMobile() != null && loginUser.getDefaultBabyId() != null){
                BindedBabyVO defaultBaby = bindedBabyService.getBindedBaby(loginUser.getDefaultBabyId(), loginUser.getParentMobile());
                month = DateUtil.betweenMonths(new Date(), defaultBaby.getBirthday()) + 1;
            }
        }

        List items = familyGameNativeRepository.getFamilyGamesByMonth(month);

        return StatusResponse.success(items);
    }

    @ApiOperation("亲子游戏详情")
    @ApiImplicitParam(name = "gameid", value="亲子游戏 id", required = true)
    @RequestMapping(value = "/family-game/{gameid}", method = RequestMethod.GET)
    public StatusResponse familyGameDetailAPI(HttpServletRequest req, HttpServletResponse resp, @PathVariable String gameid){
        FamilyGameDetailVO game = familyGameNativeRepository.getFamilyGame(gameid);
        return StatusResponse.success(game);
    }


    @ApiOperation("宝宝当天的成长指导")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "m", value = "月份， 两个字段同时使用才生效，否则使用默认宝宝"),
            @ApiImplicitParam(name = "d", value = "天")
    })
    @RequestMapping(value = "/growup-guide", method = RequestMethod.GET)
    public StatusResponse actionCallBackAPI(HttpServletRequest req, HttpServletResponse resp, Integer m, Integer d){
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");
        BindedBabyVO defaultBaby = bindedBabyService.getBindedBaby(loginUser.getDefaultBabyId(), loginUser.getParentMobile());

        int day = 0;
        int month = 0;

        if(m != null && d != null){
            day = d;
            month = m;
        }else{
            //计算入园月龄
            LocalDate currentDate = LocalDate.now();

            Date date = defaultBaby.getBirthday();
            LocalDate createdDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            Period p = Period.between(createdDate, currentDate);

            month = p.getYears() * 12 + p.getMonths();
            if(month < 0){
                throw new BusinessException(ErrorCode.BIRTHDAY_BEGGER_THAN_TODAY, "当前宝宝生日计算错误");
            }

            //计算入园天数
            day = Period.between(createdDate,currentDate).getDays();

            if(day <= 0 || day > 30){
                day = 1;
            }
        }

        List<HashMap<String, Object>> plans = growupNativeRepository.getGrowupDayPlans(month, 15888, day, 3);
        return StatusResponse.success(plans);
    }

}
